import type { QueryOptions } from '@/shared/types';
import { useQuery, useInfiniteQuery } from '@tanstack/react-query';
import { postsService } from './postsService';
import { Post, postsServiceKeys } from './domain';

interface GetPostsParams {
  page?: number;
  limit?: number;
}

export const postsOptions = (options?: QueryOptions<Post[]>) => ({
    queryKey: postsServiceKeys.posts(),
    queryFn: () => postsService.getPosts(),
    ...options,
});

export const usePosts = (options?: QueryOptions<Post[]>) => {
    return useQuery(postsOptions(options));
};

export const useInfinitePosts = (params?: GetPostsParams) => {
    return useInfiniteQuery({
        queryKey: [postsServiceKeys.posts(), params],
        queryFn: async ({ pageParam = 1 }) => {
            return postsService.getPosts({ ...params, page: pageParam as number });
        },
        initialPageParam: 1,
        getNextPageParam: (lastPage, pages) => {
            // Assuming we have more pages if we got posts
            return lastPage.length > 0 ? pages.length + 1 : undefined;
        },
    });
};